/*!
 * 浏览器本地配置存储模块
 * @author: __author__
 * @version: __buildVersion__
 * @buildDate：__buildDate__
 */
export let version: string = '__buildVersion__';

import { merge2 } from "aiv367-merge";

let setting = {
    localStorageName: 'appConfig',
    defaultConfig: {}
};

/** 获得设置 */
function getConfig(type: 'merge' | 'user' | 'default' = 'merge'): any {

    let userConfig = JSON.parse(<string>localStorage.getItem(setting.localStorageName));

    if (type === 'merge') { //默认是合并
        return merge2({}, setting.defaultConfig, userConfig);
    } else if (type === 'user') { //本地存储配置（用户配置）
        return userConfig;
    } else if (type === 'default') { //默认配置
        return setting.defaultConfig;
    }

};

/** 保存设置 */
function setConfig(config: any) {
    localStorage.setItem(setting.localStorageName, JSON.stringify(merge2({}, getConfig('user'), config)));
};

/** 删除用户设置 */
function removeConfig(cb : (userConfig: any) => void): any{
    let userConfig = getConfig('user')
    cb(userConfig);
    localStorage.setItem(setting.localStorageName, JSON.stringify(userConfig));
    return userConfig;
}

/** 重置设置 */
function resetConfig() {
    localStorage.removeItem(setting.localStorageName);
}

export default {
    setting,
    get: getConfig,
    set: setConfig,
    remove: removeConfig,
    reset: resetConfig,
}